package com.baiyue.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baiyue.entity.ProductCategory;
import com.baiyue.entity.TollRules;
import com.baiyue.exception.GlobalException;
import com.baiyue.mapper.ProductCategoryMapper;
import com.baiyue.model.SelectOptionsResult;
import com.baiyue.model.productCategory.ProductCategoryDataRequest;
import com.baiyue.model.productCategory.ProductCategoryDataResponse;
import com.baiyue.model.productInfo.ProductInfoDataRequest;
import com.baiyue.model.tollRules.TollRulesDataResponse;
import com.baiyue.result.CodeMsg;
import com.baiyue.service.ProductCategoryService;
import com.baiyue.utils.BeanMapperUtil;
import com.baiyue.utils.UserHolderUtil;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 *
 * @author 伍波
 * @date 2024-06-16
 */
@Service
public class ProductCategoryServiceImpl implements ProductCategoryService {
    private static final Logger logger = LoggerFactory.getLogger(ProductCategoryServiceImpl.class);

    @Autowired
    private ProductCategoryMapper productCategoryMapper;

    /**
     * 新增商品分类
     * @param request
     */
    @Override
    public void insert(ProductCategoryDataRequest request){
        logger.info("新增商品分类入参:{}", JSONObject.toJSONString(request));

        // 检查商品分类名称是否为空
        if (StringUtils.isEmpty(request.getCategoryName())){
            logger.warn("新增商品分类失败，商品分类名称为空");
            throw new GlobalException(CodeMsg.BIND_ERROR.fillArgs("商品分类名称"));
        }

        // 查询是否重复名称
        if (findByCategoryName(request.getCategoryName()) != null){
            logger.warn("分类名称重复！！！");
            throw new GlobalException(CodeMsg.ALREADY_EXISTS.fillArgs("分类名称"));
        }

        // 设置创建人、更新人、创建时间和更新时间90kl;iouj
        String user = UserHolderUtil.getUser().getUsername();
        request.setCreatedBy(user);
        request.setUpdatedBy(user);
        request.setCreateTime(new Date());
        request.setUpdateTime(new Date());
        if (Objects.isNull(request.getStatus())){
            request.setStatus(0);
        }

        // 将请求对象转换为实体对象并插入数据库
        ProductCategory productCategory = BeanMapperUtil.map(request, ProductCategory.class);
        productCategoryMapper.insert(productCategory);
    }

    /**
     * 获取商品分类下拉框
     * @return
     */
    @Override
    public List<SelectOptionsResult> getSelectOptions(){
        logger.info("获取商品分类下拉框");
        List<SelectOptionsResult> results = productCategoryMapper.findIdAndName();
        if (results.isEmpty()){
            logger.warn("获取商品分类下拉框为空");
            return new ArrayList<>();
        }
        return results;
    }

    /**
     * 删除商品分类（假珊瑚）
     * @param request
     * @return
     */
    @Override
    public Boolean deleteCategoryByIds(ProductCategoryDataRequest request){
        logger.info("删除商品分类入参:{}", JSONObject.toJSONString(request));
        Objects.requireNonNull(request.getIds(), () -> {
            logger.error("删除商品分类失败：ids不可为空");
            return "删除商品分类失败";
        });
        String user = UserHolderUtil.getUser().getUsername();
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("idList",request.getIds());
        paramMap.put("updateBy",user);
        Integer res = productCategoryMapper.deleteCategoryByIds(paramMap);
        return res == request.getIds().size();
    }

    /**
     * 修改分类信息
     * @param request
     */
    @Override
    public void updateCategory(ProductCategoryDataRequest request){
        logger.info("修改分类信息入参:{}", JSONObject.toJSONString(request));
        if (StringUtils.isEmpty(request.getCategoryName())){
            logger.warn("修改商品分类失败，商品分类名称为空");
            throw new GlobalException(CodeMsg.BIND_ERROR.fillArgs("商品分类名称"));
        }
        //查询是否重复名称
        ProductCategory res = findByCategoryName(request.getCategoryName());
        if (Objects.nonNull(res) && !Objects.equals(request.getId(), res.getId())){
            logger.warn("分类名称重复！！！");
            throw new GlobalException(CodeMsg.ALREADY_EXISTS.fillArgs("分类名称"));
        }
        String user = UserHolderUtil.getUser().getUsername();
        request.setUpdatedBy(user);
        request.setUpdateTime(new Date());
        ProductCategory productCategory = BeanMapperUtil.map(request, ProductCategory.class);
        productCategoryMapper.updateById(productCategory);
    }

    /**
     * 分页查询商品分类信息
     * @param request
     * @return
     */
    @Override
    public Page<ProductCategoryDataResponse> findByPage(ProductCategoryDataRequest request){
        logger.info("查询商品分类入参:{}", JSONObject.toJSONString(request));
        Page<ProductCategoryDataResponse> responsePage = new Page<>(request.getPage(),request.getSize());
        ProductCategory productCategory = BeanMapperUtil.map(request, ProductCategory.class);
        List<ProductCategory> resList = productCategoryMapper.findByPage(productCategory,responsePage);
        List<ProductCategoryDataResponse> resDataList = BeanMapperUtil.mapList(resList, ProductCategoryDataResponse.class);
        return responsePage.setRecords(resDataList);
    }

    /**
     * 根据分类名称查询
     * @param categoryName
     * @return
     */
    public ProductCategory findByCategoryName(String categoryName){
        logger.info("根据计费名称查询计费规则信息入参:{}", categoryName);
        if (StringUtils.isEmpty(categoryName)){
            throw new GlobalException(CodeMsg.BIND_ERROR.fillArgs("categoryName"));
        }
        return productCategoryMapper.findByCategoryName(categoryName);
    }
}
